package com.aliptori.fontinstaller

import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import com.aliptori.fontinstaller.Logic.LocalFontManager
import com.aliptori.fontinstaller.Logic.POKO.FontMeta
import com.github.angads25.filepicker.model.DialogConfigs
import com.github.angads25.filepicker.model.DialogProperties
import com.github.angads25.filepicker.view.FilePickerDialog
import com.ug_project.views.click
import com.yurqi.dialog.confirmDialog
import com.yurqi.dialog.messageDialog
import kotlinx.android.synthetic.main.activity_font_detail.*
import kotlinx.android.synthetic.main.content_font_detail.*

class FontDetail : AppCompatActivity() {
    private val filePickerRequestCode = 777
    private val filePicker by lazy {
        FilePickerDialog(this, DialogProperties().apply {
            selection_mode = DialogConfigs.SINGLE_MODE
            selection_type = DialogConfigs.FILE_SELECT
            root = Environment.getExternalStorageDirectory()
        })
    }

    val localFontManager by lazy { LocalFontManager(this) }
    val fontMetaFileName: String by lazy { intent.getStringExtra(LocalFontManager.fontLocalID) + ".mrm" }
    val font: FontMeta by lazy { localFontManager.getFont(fontMetaFileName) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_font_detail)
        setSupportActionBar(toolbar)

        Name.text = font.titles.zh_CN
        Designer.text = font.designers.zh_CN
        Description.text = font.descriptions.zh_CN


        Change.click {
            confirmDialog(this, title = getString(R.string.replace_description), yesStr = getString(R.string.i_m_continue), noStr = getString(R.string.cancel)) {
                filePicker.setDialogSelectionListener {
                    val file = it[0]
                    if (!file.endsWith(".ttf")) {
                        messageDialog(this, title = getString(R.string.wrong_font_file))
                        return@setDialogSelectionListener
                    }
                    val result = localFontManager.replaceNewFont(font, file)

                    if (result == null) {
                        messageDialog(this, title = getString(R.string.replace_successfully)){
                            finish()
                        }
                    } else {
                        messageDialog(this, title = getString(R.string.replace_error) + getString(R.string.error_message_is) + result!!.message)
                    }
                }
                filePicker.show()
            }
        }
    }
}
